package com.console.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.nio.ch.FileKey;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
public class FileUploadController {

    private Logger logger= LoggerFactory.getLogger(getClass().getName());

    @Value("${web.upload-path}")
    String fileDir;

    @PostMapping("upload")
    public Map upload(MultipartFile file, HttpServletRequest request){
        String realPath = fileDir;

        File folder= new File(realPath);

        if (!folder.exists()){
            folder.mkdirs();
        }

        String oldName=file.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));

        Map<String,Object> result=new HashMap<>();

        try {
            file.transferTo(new File(folder,newName));
            String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/file/"+newName;
            result.put("status","ok");
            result.put("url",url);
            logger.info("upload file "+newName);


        } catch (IOException e) {
            result.put("status","failed");
            result.put("msg",e.getMessage());
            logger.info("upload file failed "+oldName);
        }


        return result;
    }

    @PostMapping("uploadMul")
    public Map upload(MultipartFile[] files, HttpServletRequest request){
        Map<String,Object> result=new HashMap<>();
        int count=0;
        List<Map<String,Object>> list=new ArrayList<>();

        if (files==null|| files.length==0){
            result.put("","failed");
            result.put("msg","no file");
            return result;
        }

        for (MultipartFile file : files) {
            Map<String,Object>  map=new HashMap<>();
            Map res = upload(file, request);
            map.put("name",file.getOriginalFilename());
            Object url = res.get("url");
            if (url!=null){
                count++;
                map.put("url",url);
                map.put("status","ok");
            }else {
                map.put("status","failed");
                map.put("msg",res.get("msg"));
            }
            list.add(map);
        }

        result.put("upload",files.length);
        result.put("succeed",count);
        result.put("detail",list);


        return result;
    }

}
